﻿/**
 * Created with IntelliJ IDEA.
 * User: render
 * Date: 12-10-26
 * Time: 上午10:13
 * To change this template use File | Settings | File Templates.
 */

fl.runScript(fl.configURI + "jsfl/sugar.jsfl");
fl.runScript(fl.configURI + "jsfl/MyExt.jsfl");

/**
 * 过滤器工厂
 * @param selector
 * @return {LibItemFilter}
 */
function jsfl(selector){
    var _selector = selector.trim();
    switch(selector){
        case "lib":
            return new LibItemFilter();
        case "ele":
            return new DomElementFilter();
        case "sel":
            return;
    }
}

/**
 * 是否为正则表达式
 * @param obj
 * @return {Boolean}
 */
jsfl.is_reg = function(obj){
    return obj instanceof  RegExp;
}

/**
 * 配置
 * @type {Object}
 */
jsfl.config = {
    itemTypes:{
        comp:"component",
        cpcl: "compiled clip",
        mc: "movie clip",
        gph: "graphic",
        btn: "button",
        fld: "folder",
        font: "font",
        bmp: "bitmap",
        snd: "sound",
        scn: "screen",
        vid: "video"
    },
    instTypes: {
        sb: "symbol",
        bmp: "bitmap",
        evid: "embedded video",
        lvid: "linked video",
        vid: "video",
        cpcl: "compiled clip"
    },
    regPoint: {
        tl: "top left",
        tc: "top center",
        tr: "top right",
        cl: "center left",
        c: "center",
        cr: "center right",
        bl: "bottom left",
        bc: "bottom center",
        br: "bottom right"
    }
};

/**
 * 过滤不匹配名字的元素
 * @param arr
 * @param pattern
 * @return {*}
 */
function filter_name(arr, pattern){
    var is_reg = jsfl.is_reg(pattern);

    return arr.filter(function(item){
        if(is_reg){
            return pattern.test(item.name);
        }
        else{
            return (pattern.trim() == item.name);
        }
    });
}

var $ = $ || jsfl;

/**
 * 文档对象
 * @return {Document}
 */
function dom(){
    return fl.getDocumentDOM();
}

/**
 * 库
 * @return {library}
 */
function lib(){
    return dom().library;
}

/**
 * 时间轴
 * @return {Timeline}
 */
function tl(){
    return dom().getTimeline();
}

/**
 * 当前所有（选择）图层
 * @param selected
 * @return {Array}
 */
function layers(selected){
    return selected? tl().getSelectedLayers() : tl().layers;
}

function cur_layer(){
    return layers()[tl().currentLayer];
}

/**
 *
 * @param selection
 * @return {Fill}
 */
function fll(selection){
    return dom().getCustomFill(selection? "selection" : "toolbar");
}

/**
 * 笔触
 */
function stk(){
    return dom().getCustomStroke();
}

function tool(){
    return fl.tools;
}

function add2dom(obj, name){
    lib().addItemToDocumen(obj, name);
}

/**
 * 库中所有（被选）元素
 * @param selected
 * @return {Array}
 */
function lib_its(selected){
    var its = lib().items;
    if(selected){
        its = its.filter(function(item){
            return (lib().getSelectedItems().indexOf(item) > -1)
        });
    }
    return its;
}

/**
 * 当前所选帧上的所有元素
 * @param selected     是否只提取被选中的元素
 * @return {Array}
 */
function frm_eles(selected){
    var f = tl().currentFrame;
    var ls = layers();
    var arr = [];
    for(var i = 0; i < ls.length; i++){
        var l = ls[i];
        var fes = l.frames[f].elements;
        if(selected){
            fes = fes.filter(function(item){
                return dom_eles().indexOf(item) > -1;
            });
        }
        arr = arr.concat(fes);
    }
    return arr;
}

/**
 * 文档对象当前选择的元素
 * @return {*}
 */
function dom_eles(){
    return dom().selection;
}

/**
 * library item of element
 * @param inst
 * @return {*}
 */
function ioe(inst){
    return inst.libraryItem;
}

/**
 * 库项目名称的文件夹路径及名称
 * @param item
 * @return {*}
 */
function nd(item){
    if(item instanceof Instance){
        return ['', ''];
    }
    else if(item instanceof Layer){
        return ['', ''];
    }
    else{
        var parts = item.name.split("/");
        return [parts[parts.length - 1] || '', parts.slice(0, parts.length - 1).join('/') || ''];
    }
}

function p2uri(path){
    return "file:///" + path.replace(":", "|");
}

function cen_ele(ele, dir){
    if(dir && dir.indexOf('v') > -1){
        e.y = (dom().height - e.height) / 2;
    }
    if(dir && dir.indexOf('h') > -1){
        e.x = (dom().width - e.width) / 2;
    }
}

function top_ele(ele, dir){
    if(dir && dir.indexOf('v') > -1){
        e.y = 0;
    }
    if(dir && dir.indexOf('h') > -1){
        e.x = 0;
    }
}

function bot_ele(ele, dir){
    var d = dom();
    if(dir && dir.indexOf('v') > -1){
        e.y = d.height - e.height;
    }
    if(dir && dir.indexOf('h') > -1){
        e.x = d.width - e.width;
    }
}

function get_files(path, dOrF){
    var f = (dOrF && dOrF.indexOf('f') > -1)? 'files' : '';
    var d = (dOrF && dOrF.indexOf('d') > -1)? 'directories' : '';
    var t = (f && d)? '' : (f || d);
    return FLfile.listFolder("file:///" + path.replace(':', '|'));
}

/**
 * 创建符号
 * @param type
 */
function create_sb(type){
    var lib = $();
    lib.addNewItem($.config.itemTypes[type]);
    if (lib.getItemProperty('linkageImportForRS') == true) {
        lib.setItemProperty('linkageImportForRS', false);
    }
    else {
        lib.setItemProperty('linkageExportForAS', false);
        lib.setItemProperty('linkageExportForRS', false);
    }
}

function export_item(item, id, cls){
    item.linkageExportForAS = true;
    if(id){ item.linkageClassName = id; }
    if(cls){ item.linkageBaseClass = cls; }
    item.linkageExportInFirstFrame = true;
    item.linkageExportForAS = true;
}



/*
 *过滤器命名规范：
 *由于windows下文件名禁用符号： \ / : * " < > | ?
 *因此可以用以上字符及其他字符作为特殊过滤字符
 * ".class"   某一种类型为class的项
 * "#name"    全名为name的项
 * ">parname" 父层级名称为parname的项
 * "*"        所有项
 * "?subname" 名字中包含subname的项
 * "^subname" 名字中以subname开头的项
 * "$subname" 名字中subname结尾的项
 * "/reg/"    名字匹配正则表达式的项
 * ":"        状态标识---
 *  ":sel"    被选择
 *  ":unsel" 未被选择
 */

/**
 * 库元素过滤器
 * @constructor
 */
function LibItemFilter(){
    var _items = lib_its();
    this.items = _items;

    this.reset = function(){
        _items = this.items;
        return this;
    }

    //get items
    this.get = function(index){
        return (index === undefined? _items : _items[index]);
    }

    //do how many times
    this.run = function(st, end){
        _items = _items.slice(st, end);
        return this;
    }

    //name
    this.n = function(selector){
        _items = filter_name(_items, selector);
        return this;
    }

    //type
    this.t = function(type){
        _items = _items.filter(function(item){
            return item.itemType == jsfl.config.itemTypes[type];
        });
        return this;
    }

    //selected
    this.s = function(unselect){
        var sel_arr = lib().getSelectedItems();

        _items = _items.filter(function(item){
            var in_sel = (sel_arr.indexOf(item) > -1);
            return (unselect? !in_sel : in_sel);
        });
        return this;
    }

    //parent
    this.p = function(pattern, lv){
        var is_reg = jsfl.is_reg(pattern);

        _items = _items.filter(function(item){
            var pars = item.name.split("/");
            if(pars.length > 1){
                var len = pars.length - 1;
                for(var i = (lv? lv - 1 : 0); i < len && len >= (lv? lv : 0) ; i++){
                    if(is_reg){
                        var match = pattern.test(pars[i]);
                        if(lv > 0){
                            return match;
                        } else{
                            continue;
                        }
                    }
                    else{
                        var eql = pattern == pars[i];
                        if(lv > 0){
                            return eql;
                        }else{
                            continue;
                        }
                    }
                }
            }
            else{
                return false;
            }
        });
    }

    //设置宽度
    this.w = function(width){
        _items.forEach(function(item){
            item.width = width;
        });
        return this;
    }

    //设置高度
    this.h = function(height){
        _items.forEach(function(item){
            item.height = height;
        });
        return this;
    }
}

/**
 * 舞台元素过滤器
 * @param pattern
 * @constructor
 */
function DomElementFilter(pattern){
    var _items = frm_eles();
    this.items = _items;

    //重置结果数组
    this.reset = function(){
        _items = this.items;
        return this;
    }

    //get items
    this.get = function(index){
        return index === undefined? _items : _items[index];
    }

    //do how many times
    this.run = function(st, end){
        _items = _items.slice(st, end);
        return this;
    }

    //name
    this.n = function(selector){
        _items = filter_name(_items, selector);
        return this;
    }

    //type
    this.t = function(type){
        _items = _items.filter(function(item){
            return item.instanceType == jsfl.config.instTypes[type];
        });
        return this;
    }

    //selected
    this.s = function(unselect){
        _items = _items.filter(function(item){
            return item.selected && !unselect;
        });
        return this;
    }

    //item name
    this.it_n = function(pattern){
        var is_reg = jsfl.is_reg(pattern);
        _items = _items.filter(function(inst){
            if(is_reg){
                return  pattern.test(inst.libraryItem.name);
            }
            else{
                return inst.libraryItem.name.trim() == pattern;
            }
        })
        return this;
    }

    //item type
    this.it_t = function(pattern){
        _items = _items.filter(function(inst){
            return inst.itemTypes == jsfl.config.itemTypes[pattern];
        });
    }

    //设置宽度
    this.w = function(width){
        _items.forEach(function(item){
            item.width = width;
        })
    }

    //设置高度
    this.h = function(height){
        _items.forEach(function(item){
            item.height = height;
        });
    }

    //所属的库元素
    this.li = function(){
        return _items.p_arr("libraryItem");
    }

    //进入编辑模式并执行动作
    this.edit = function(fn, mode){
        var d = dom();
        var last_sl = d.selection;
        for(var i = 0; i < _items.length; i++){
            var item =_items[i];
            if(item.instanceType != jsfl.config.instTypes.sb) {
                continue;
            }
            d.selectNone();
            d.selection = [item];
            d.enterEditMode(mode? mode : "inPlace");
            fn && fn(item, i);
            d.exitEditMode();
            d.selection = last_sl;
        }
        d.selection = last_sl;
        return this;
    }

    //conver elements to symbols
    this.e2sb = function(type, post_fn, reg){
        var d = dom();
        var last_sl = d.selection;
        _items.forEach(function(inst, index){
            d.selectNone();
            d.selection = [inst];
            //converToSymbol can't send name contain folder, so set name again after execute it....
            var it = d.convertToSymbol(type, '', jsfl.config.regPoint[reg]);
            post_fn(inst, it, index);
        });
        d.selection = last_sl;
        return this;
    }
}

//alert(dom().convertToSymbol('movie clip', 'desc/zdc', 'top left'));





